package com.bms.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import com.bms.domain.Groups;
import com.bms.domain.User;

public class UserDao {
	
	private JdbcTemplate jdbcTemplate;
	private GroupsDao groupsDao;

	public void setGroupsDao(GroupsDao groupsDao) {
		this.groupsDao = groupsDao;
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	public boolean auth(User user) {
		String sql = "select count(*) from bms_users where username=? and password=?";
		int r = this.jdbcTemplate.queryForInt(sql,new Object[]{user.getUsername(),user.getPassword()});
		if(r>0) return true;
		else return false;
	}

	@SuppressWarnings("unchecked")
	public List<User> getList() {
		String sql = "select * from bms_users order by id desc";
		List<User> list = this.jdbcTemplate.query(sql,new rowMapper());
		return list;
	}

	public User getUser(String username) {
		String sql = "select * from bms_users where username=?";
		User user = (User) this.jdbcTemplate.queryForObject(sql,new Object[]{username},new rowMapper());
		return user;
	}
	
	public User getUserFromId(String id){
		String sql = "select * from bms_users where id=?";
		User user = (User) this.jdbcTemplate.queryForObject(sql,new Object[]{id},new rowMapper());
		return user;
	}

	public void save(User user) {
		String sql = "UPDATE bms_users SET password=? where username=?";
		this.jdbcTemplate.update(sql,new Object[]{
				user.getPassword(),
				user.getPassword()
		});
	}

	public void add(User user) {
		String sql = "INSERT INTO bms_users VALUES(default,?,?,?,?,?)";
		this.jdbcTemplate.update(sql,new Object[]{
				user.getUsername(),
				user.getPassword(),
				user.getNickname(),
				user.getGroups().getId(),
				user.getStatus()
		});
	}

	public boolean checkUserExist(User user) {
		String sql = "select count(*) form bms_users where username=?";
		int r = this.jdbcTemplate.queryForInt(sql,new Object[]{user.getUsername()});
		if(r>0) return true;
		else return false;
	}
	
	public class rowMapper implements RowMapper {
		@Override
		public Object mapRow(ResultSet rs, int row) throws SQLException {
			User u = new User();
			u.setId(rs.getString("id"));
			u.setUsername(rs.getString("username"));
			u.setPassword(rs.getString("password"));
			u.setNickname(rs.getString("nickname"));
			String groupId = rs.getString("groups");
			Groups group = groupsDao.get(groupId);
			u.setGroups(group);
			u.setStatus(rs.getInt("status"));
			return u;
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<User> getUsersFromGroupsId(String groupsId){
		String sql = "select * from bms_users where groups=?";
		List<User> list = this.jdbcTemplate.query(sql,new Object[]{groupsId},new rowMapper());
		return list;
	}
}
